package com.zk.config.web.op;

import java.util.List;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.zkclient.ZkClient;
import com.github.zkclient.ZkConnection;
import com.zk.config.web.model.TreeData;
import com.zk.config.web.model.ZkCache;
import com.zk.config.web.util.ZkCacheUtil;

public class MyZkClient extends ZkClient {
	
	private Logger log = LoggerFactory.getLogger(MyZkClient.class);
	
	public MyZkClient(String connectString) {
		super(connectString);
	}
	
	public MyZkClient(String connectString, int connectionTimeout) {
		super(connectString, 30000, connectionTimeout);
	}

	public MyZkClient(String connectString, int sessionTimeout, int connectionTimeout) {
		super(new ZkConnection(connectString, sessionTimeout), connectionTimeout);
	}
	
	@Override
	public void process(WatchedEvent event) {
		if(ZkCache.useCache) {
			String path = event.getPath();
			if (event.getType() != EventType.None && path != null) {
				try {
					if(event.getType() == EventType.NodeDeleted) {
						// 清缓存
						ZkCacheUtil.deleteNodeClearCache(path);
					} else if (event.getType() == EventType.NodeCreated) {
						getZooKeeper().exists(path, true); // 回调继续监听监听变更的路径节点
						// 清缓存
						ZkCacheUtil.createNodeSetCache(path);
					} else if(event.getType() == EventType.NodeDataChanged) {
						getZooKeeper().exists(path, true); // 回调继续监听监听变更的路径节点
						// 清缓存
						ZkCacheUtil.changeNodeSetCache(path);
					} else if(event.getType() == EventType.NodeChildrenChanged) {
						// 继续监听监听变更的路径节点
						TreeData td = ZkCache.zkData.get(path);
						if(td != null) {
							List<TreeData> ctdList = td.getChildren();
							if(ctdList != null) {
								ZkCacheUtil.getChildrenSetCache(getZooKeeper(), path, ctdList, true);
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e.getMessage());
				}
			}
		}
		super.process(event);
		if(ZkCache.useCache) {
			if (event.getState() == KeeperState.Expired) {
				ZkCache.zkData.clear();
			}
		}
	}
}
